package com.fast.controller.thread.task;

import com.baomidou.mybatisplus.extension.api.R;
import com.fast.controller.delay.Order;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Callable;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author hujw
 * @since 2021/12/20
 */
@Component
@Slf4j
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class FutureTestTask implements Callable {

    private Integer id;

    public void setId(Integer id) {
        this.id = id;
    }

    @Override
    public R call() throws Exception {
        log.info("线程:【{}】执行的id为:{}", Thread.currentThread().getName(), id);
//        Thread.sleep(1000);
        Order test1 = new Order("test1" + id, 5, TimeUnit.SECONDS,"dfsf");
        DelayQueue<Order> delayQueue = new DelayQueue<>();
        delayQueue.put(test1);
        System.out.println(test1.name + "订单延迟队列开始时间:" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        while (delayQueue.size() != 0) {
            /**
             * 取队列头部元素是否过期
             */
            Order task = delayQueue.poll();
            if (task != null) {
                System.out.format("订单:{%s}被取消, 取消时间:{%s}\n", task.name, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        }

        return R.ok("测试id:" + id);
    }
}
